package com.tyqx.hashchainbiz.controller.jzt;

//// import com.alibaba.fastjson.JSON;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tyqx.hashchainbean.module.*;
import com.tyqx.hashchainbean.vo.*;
import com.tyqx.hashchainbiz.controller.config.JwtTokenUtil;
import com.tyqx.hashchainbiz.service.*;
import com.tyqx.hashchainutil.common.*;
import com.tyqx.hashchainutil.common.mongodb.ImagePathHashValueUtil;
import com.tyqx.hashchainutil.common.mongodb.MongoDBUtil;
import hashchainutil.common.Dto;
import hashchainutil.common.DtoUtil;
import hashchainutil.common.EmptyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(description = "JZT追溯信息")
@RestController
@RequestMapping("/JZTApi/logistics")
@CrossOrigin
public class JZTLogisticsController {

    @Resource
    private JZTLogisticsService jztLogisticsService;

    @Resource
    private JZTLogisticsRelationshipService jztLogisticsRelationshipService;

    @Resource
    private TrackUserService trackUserService;

    @Resource
    private MongoDBUtil mongoDBUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private MysqlDataBaseAndMongDbConfigService mysqlDataBaseAndMongDbConfigService;

    @Resource
    private HashChainStatisticsService hashChainStatisticsService;

    /*@ApiOperation(value = "添加追溯信息", httpMethod = "POST")
    @RequestMapping(value = "/addJZTLogistics", method = RequestMethod.POST)
    @ResponseBody
    public Dto addJZTLogistics(@RequestBody JZTLogistics jztLogistics) throws Exception {
        if (true){
            return null;
        }
        String msg = "";
        Future<String> future = jztLogisticsService.addJZTLogistics(jztLogistics);
        msg = "添加追溯信息成功";
        return DtoUtil.returnSuccess(msg);
    }*/

    @ApiOperation(value = "添加追溯信息", httpMethod = "POST")
    @RequestMapping(value = "/addJZTLogistics", method = RequestMethod.POST)
    @ResponseBody
    public Dto addJZTLogistics(@RequestBody JZTLogistics jztLogistics, HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String tokenUserName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        String userName = jztLogistics.getUserName();
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        if (EmptyUtils.isEmpty(trackUser)) {
            String msg = "用户找不到";
            return DtoUtil.returnFail(msg, "100006");
        }

        if (!tokenUserName.equals(userName)) {
            String msg = "用户名跟token用户名不匹配";
            return DtoUtil.returnFail(msg, "100005");
        }
        String msg = "";

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;

        List<JZTLogistics> jztLogisticsList=new ArrayList<>();
        boolean flag=false;
        jztLogisticsList.add(jztLogistics);

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztLogisticsList.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztLogisticsList);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue);
            mongoDbInfoVO.setInfoList(jztLogisticsList);
            mongoDbInfoVO.setInfoTableName("jzt_logistics");

            String collName = "jztLogisticsList";


            double dataCount = jztLogisticsList.size();
            String dataType = "jztLogisticsList";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztLogisticsList.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            /*Integer flag=hashChainStatisticsService.add(hashChainStatistics);
            flag=0;
            if (flag == 0){
                throw new Exception("record statistcs error");
            }
            mongoDBUtil.insertOne(collName,mongoDbInfoVO);*/
            flag=mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }
        if (flag) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else {
            msg = "信息上链失败";
            return DtoUtil.returnFail(msg, "100001");
        }
    }

    @ApiOperation(value = "批量添加追溯信息", httpMethod = "POST")
    @RequestMapping(value = "/batchAddJZTLogistics", method = RequestMethod.POST)
    @ResponseBody
    public Dto batchAddJZTLogistics(@RequestBody List<JZTLogistics> jztLogisticsList, HttpServletRequest request) throws Exception {
        // verify token username against data username
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        List<JZTLogistics> jztLogisticsListError = new ArrayList<>();
        int size = jztLogisticsList.size();
        for (int i = 0; i < size; i++) {
            JZTLogistics jztLogistics = jztLogisticsList.get(i);
            if (EmptyUtils.isEmpty(trackUser) || !userName.equals(jztLogistics.getUserName())) {
                jztLogisticsListError.add(jztLogistics);
            }
        }
        if (jztLogisticsListError.size() > 0) {
            for (int j = 0; j < jztLogisticsListError.size(); j++) {
                jztLogisticsList.remove(jztLogisticsListError.get(j));
            }
        }
        String msg = "";

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztLogisticsList.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztLogisticsList);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue);
            mongoDbInfoVO.setInfoList(jztLogisticsList);
            mongoDbInfoVO.setInfoTableName("jzt_logistics");

            String collName = "jztLogisticsList";


            double dataCount = jztLogisticsList.size();
            String dataType = "jztLogisticsList";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztLogisticsList.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            /*Integer flag=hashChainStatisticsService.add(hashChainStatistics);
            flag=0;
            if (flag == 0){
                throw new Exception("record statistcs error");
            }
            mongoDBUtil.insertOne(collName,mongoDbInfoVO);*/
            mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }

        if (jztLogisticsListError.size() == 0 && EmptyUtils.isNotEmpty(mongoDbInfoVO.getId())) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else if (jztLogisticsList.size() == 0 && jztLogisticsListError.size() > 0) {
            msg = "信息上链失败,信息包含的用户名不正确";
            return DtoUtil.returnFail(msg, "100001");
        } else {
            msg = "success: " + jztLogisticsList.size() + ", fail: " + jztLogisticsListError.size() + ",用户名不正确信息上链失败";
            return DtoUtil.returnSuccess(msg, "100002");
        }
    }

    @ApiOperation(value = "根据追溯码查询追溯信息", httpMethod = "POST")
    @RequestMapping(value = "/getJZTLogisticsByTraceabilityCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTLogisticsByTraceabilityCode(@RequestParam(value = "traceabilityCode", required = true) String traceabilityCode, HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);

        List<String> parentTraceabilityCodeStr = jztLogisticsRelationshipService.getParentTraceabilityCodeByTraceabilityCode(traceabilityCode);
        String[] parentTraceabilityCodes = parentTraceabilityCodeStr.get(0).split(",");
        List<String> traceabilityCodes = new ArrayList<>();
        for (int i = 0; i < parentTraceabilityCodes.length; i++) {
            if (EmptyUtils.isNotEmpty(parentTraceabilityCodes[i])) {
                traceabilityCodes.add(parentTraceabilityCodes[i]);
            }
        }
        //traceabilityCodes.add(traceabilityCode);
        List<JZTLogisticsVO> jztLogistics = jztLogisticsService.grantGetJZTLogisticsByTraceabilityCode(traceabilityCodes,userName);
        if (jztLogistics.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztLogistics);
        } else {
            return DtoUtil.returnSuccess("未查询到记录", "");
        }
    }

    @RequestMapping(value = "/getJZTLogisticsAndGS1ByTraceabilityCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTLogisticsAndGS1ByTraceabilityCode(@RequestParam(value = "traceabilityCode", required = true) String traceabilityCode, HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);

        List<String> parentTraceabilityCodeStr = jztLogisticsRelationshipService.getParentTraceabilityCodeByTraceabilityCode(traceabilityCode);
        String[] parentTraceabilityCodes = parentTraceabilityCodeStr.get(0).split(",");
        List<String> traceabilityCodes = new ArrayList<>();
        for (int i = 0; i < parentTraceabilityCodes.length; i++) {
            if (EmptyUtils.isNotEmpty(parentTraceabilityCodes[i])) {
                traceabilityCodes.add(parentTraceabilityCodes[i]);
            }
        }
        //traceabilityCodes.add(traceabilityCode);
        List<JZTLogisticsAndGS1VO> jztLogistics = jztLogisticsService.grantGetJZTLogisticsAndGS1ByTraceabilityCode(traceabilityCodes,userName);
        if (jztLogistics.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztLogistics);
        } else {
            return DtoUtil.returnSuccess("未查询到记录", "");
        }
    }


    @ApiOperation(value = "根据追溯码查询追溯信息1", httpMethod = "POST")
    @RequestMapping(value = "/getJZTLogisticsByTraceabilityCodeTest", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTLogisticsByTraceabilityCodeTest(@RequestParam(value = "traceabilityCode", required = true) String traceabilityCode) throws Exception {
        List<JZTLogisticsVO> jztLogistics = jztLogisticsService.getJZTLogisticsByCode(traceabilityCode);
        if (jztLogistics.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztLogistics);
        } else {
            return DtoUtil.returnFail("未查询到记录", "10001");
        }
    }

    @RequestMapping(value = "/getSelectAll", method = RequestMethod.POST)
    @ResponseBody
    public Dto getSelectAll() throws Exception {
        List<JZTLogisticsDataVO> jztLogisticsDataVOList = jztLogisticsService.selectAll();
        return DtoUtil.returnCodeSuccess("", jztLogisticsDataVOList);
    }
}
